package com.memeuxe.awtrix.util;

import cn.hutool.core.io.file.FileReader;
import com.memeuxe.awtrix.entity.Command;
import lombok.extern.slf4j.Slf4j;
import org.quartz.CronExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.File;
import java.time.Instant;
import java.util.AbstractQueue;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;

@Component
@Slf4j
public class CommandCache implements ApplicationRunner {
    public static ArrayBlockingQueue<Command> commandQueue = new ArrayBlockingQueue<Command>(15);
    public static List<Command> commandList = new ArrayList<>();
    public static Instant lastRunEndTime = Instant.now();

    @Value("${item.command.dir}")
    private String ITEM_COMMAND_DIR;
    @Autowired
    private CommandHttpSend commandHttpSend;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        if(StringUtils.isEmpty(ITEM_COMMAND_DIR)){
            throw new Exception("item.command.dir未配置");
        }
        File dir = new File(ITEM_COMMAND_DIR);
        if(dir == null || !dir.exists() || dir.isFile()){
            throw new Exception("item.command.dir路径不存在");
        }
        File[] files = dir.listFiles();
        FileReader reader;
        List<String> contents;
        Command command;
        for(File temp : files){
            reader = new FileReader(temp);
            contents = reader.readLines();
            command = new Command();
//            private String name;
//            private String type;//类型，basic/draw
//            private String cron;
//            private CronExpression cronE;
//            private Integer expend;//耗时，单位分
//            private String commandStr;
            command.setName(contents.get(0));
            command.setType(contents.get(1));
            command.setCron(contents.get(2));
            command.setCronE(new CronExpression(command.getCron()));
            command.setExpend(Integer.parseInt(contents.get(3)));
            command.setCommandStr(contents.get(4));
            log.info("command={}", command.toString());
            commandList.add(command);
        }
        // 开始运行发送程序
        CommandSendThread thread = new CommandSendThread(commandHttpSend);
        thread.start();
    }
}
